from . import mon_bp
from flask import render_template,jsonify,make_response,request
from flask_restful import Api,Resource
from model.monitor import disk_t
from lib.response import response
from mail.mail_warn import warn
from model.user import host

api = Api(mon_bp)

class disk(Resource):
    def get(self, id=None):
        if id is None:
            result = disk_t.get()
        else:
            result = disk_t.get_by_id(id)
        result = response(data=result, message="get disk innfo success")

        # return result
        return make_response(render_template('disk_monitor.html',data = result),200)

    def post(self):

        hostname = request.json.get("hostname")
        date = request.json.get("date")
        f_type = request.json.get("f_type")
        used = request.json.get("used")
        free = request.json.get("free")
        total = request.json.get("total")
        used_percent = request.json.get("used_percent")
        mountpoint = request.json.get("mountpoint")

        disk_t.create(hostname,date,f_type,used,free,total,used_percent,mountpoint)
        email_t = host.query.filter_by(hostname=hostname).first().user_info.email
        warn.disk_warn(used_percent,hostname,email_t)
        return response(message="create disk_info success")

    def put(self, id):

        hostname = request.json.get("hostname")
        date = request.json.get("date")
        f_type = request.json.get("f_type")
        used = request.json.get("used")
        free = request.json.get("free")
        total = request.json.get("total")
        used_percent = request.json.get("used_percent")
        mountpoint = request.json.get("mountpoint")

        disk_t.update(id,hostname,date,f_type,used,free,total,used_percent,mountpoint)
        return response(message="update disk_info success")

    def delete(self, id):
        disk_t.delete(id)
        return response(message="delete disk_info success")

api.add_resource(disk,'/disk')
api.add_resource(disk,'/disk/<int:id>',endpoint='diskid')
